<script setup lang="ts">
import { CirclePlus, Refresh, RefreshRight, Search } from "@element-plus/icons-vue"
import { reactive, ref, watch } from "vue"
import { AddGradeApi, DeleteGradeApi, FindGradeByCondApi, UpdateGradeApi } from "@/api/grade"
import { usePagination } from "@/hooks/usePagination"
import { IAddGradeRequestData, IAddGradeResponseData } from "@/api/grade/types/grade"
import { IGetAdminByNameData } from "@/api/admin/types/admin"
import { getAdminByNameDataApi } from "@/api/admin"
import { GetProjectIdAndNameList } from "@/api/project"
import { IGetProjectIdAndNameResponseData } from "@/api/project/types/project"
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus"
import { useUserStore } from "@/store/modules/user"
import { IGetDepartmentData } from "@/api/department/types/department"
import { getDepartmentIdAndNameList } from "@/api/department"
import { IUserInfoData } from "@/api/login/types/login"
import { IAddGraduateStudentsRequestData } from "@/api/student/types/student"
import { graduateStudentsApi } from "@/api/student"
import { hasAnthority } from "@/utils"

const loading = ref(false)
const userStore = useUserStore()
const userInfo = userStore.userInfo as IUserInfoData
const searchData = reactive<{
  name: string
  year: string
  seq: string
  projectId: number | undefined
  departmentId: number | undefined
}>({
  name: "",
  year: "",
  seq: "",
  projectId: undefined,
  departmentId: userInfo.departmentId
})

// 查询
const DepartmentData = ref<IGetDepartmentData[]>([])
const GradeData = ref<IAddGradeResponseData[]>([])
const AdminData = ref<IGetAdminByNameData[]>([])
const ProjectData = ref<IGetProjectIdAndNameResponseData[]>([])
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const refreshing = ref(false)
const getGradeDataList = () => {
  if (refreshing.value) return
  refreshing.value = true
  loading.value = true
  FindGradeByCondApi({
    page: paginationData.currentPage,
    size: paginationData.pageSize,
    name: searchData.name,
    year: searchData.year,
    seq: searchData.seq,
    projectId: searchData.projectId,
    departmentId: searchData.departmentId
  })
    .then((res) => {
      paginationData.total = res.data.total
      GradeData.value = res.data.list
    })
    .catch(() => {
      GradeData.value = []
    })
    .finally(() => {
      refreshing.value = false
      loading.value = false
    })
}
getGradeDataList()
const getDepartmentDataList = () => {
  getDepartmentIdAndNameList({ name: "", departmentId: userInfo.departmentId })
    .then((res) => {
      DepartmentData.value = res.data.list
    })
    .catch(() => {
      DepartmentData.value = []
    })
}
getDepartmentDataList()
const getAdminDataList = () => {
  getAdminByNameDataApi({ name: "", departmentId: userInfo.departmentId })
    .then((res) => {
      AdminData.value = res.data.users
    })
    .catch(() => {
      AdminData.value = []
    })
}

const getProjectData = ref<{
  name: string
  departmentId: undefined | number
}>({
  name: "",
  departmentId: userInfo.departmentId
})

const getProjectDataList = () => {
  GetProjectIdAndNameList(getProjectData.value)
    .then((res) => {
      ProjectData.value = res.data.list
    })
    .catch(() => {
      ProjectData.value = []
    })
}

watch([() => getProjectData.value.departmentId], () => {
  if (userInfo.authority === "2") {
    searchData.projectId = undefined
    getProjectDataList()
  }
})

getAdminDataList()
getProjectDataList()
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getGradeDataList()
  }
  paginationData.currentPage = 1
}
const resetSearch = () => {
  searchData.name = ""
  searchData.projectId = undefined
  searchData.year = ""
  searchData.seq = ""
  searchData.departmentId = undefined
  if (paginationData.currentPage === 1) {
    getGradeDataList()
  }
  paginationData.currentPage = 1
}

// 新增
const addFormRef = ref<FormInstance | null>(null)
const addFormRules: FormRules = reactive({
  name: [{ required: true, trigger: "blur", message: "请输入班级名称" }],
  year: [{ required: true, trigger: "blur", message: "请输入年级" }],
  seq: [{ required: true, trigger: "blur", message: "请输入班级" }],
  projectId: [{ required: true, trigger: "blur", message: "请选择项目" }]
})
const addFormData = reactive<IAddGradeRequestData>({
  year: "",
  seq: undefined,
  projectId: undefined,
  note: "",
  name: "",
  teacherPhone: "",
  teacherName: ""
})
const addDialogVisible = ref(false)
const handleCreate = () => {
  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (currentUpdateId.value === undefined) {
        AddGradeApi(addFormData).then(() => {
          ElMessage.success("新增成功")
          addDialogVisible.value = false
          getGradeDataList()
        })
      } else {
        UpdateGradeApi({
          id: currentUpdateId.value,
          ...addFormData
        }).then(() => {
          ElMessage.success("修改成功")
          addDialogVisible.value = false
          getGradeDataList()
        })
      }
    } else {
      return false
    }
  })
}

const addInfoFormRef = ref<FormInstance | null>(null)
const addInfoDialogVisible = ref(false)
const addInfoFormRules: FormRules = reactive({
  year: [{ required: true, trigger: "blur", message: "请选择结业年份" }],
  trainingInfo: [{ required: true, trigger: "blur", message: "请输入结业信息" }],
  creationTime: [{ required: true, trigger: "blur", message: "请选择证书生成时间" }]
})
const addInfoFormData = ref<IAddGraduateStudentsRequestData>({
  classId: undefined,
  year: "",
  creationTime: "",
  trainingInfo: "",
  departmentId: userInfo.departmentId
})
const handleConfirmAdd = () => {
  loading.value = true
  graduateStudentsApi(addInfoFormData.value)
    .then(() => {
      ElMessage.success("添加成功")
      addInfoDialogVisible.value = false
    })
    .finally(() => {
      loading.value = false
    })
}

const currentUpdateInfoId = ref<undefined | number>(undefined)
const handleAdd = (row: IAddGradeResponseData) => {
  if (row.trainingInfo) {
    currentUpdateInfoId.value = row.id
    addInfoFormData.value.trainingInfo = row.trainingInfo
    addInfoFormData.value.year = row.year + ""
    addInfoFormData.value.creationTime = row.creationTime
  }
  addInfoFormData.value.classId = row.id
  // addInfoFormData.value.creationTime = row.cre
  addInfoDialogVisible.value = true
}
//#region 改
const currentUpdateId = ref<undefined | number>(undefined)
const handleUpdate = (row: IAddGradeResponseData) => {
  currentUpdateId.value = row.id
  addFormData.seq = row.seq
  addFormData.year = row.year + ""
  addFormData.projectId = row.projectId
  addFormData.note = row.note
  addFormData.name = row.name
  addFormData.teacherPhone = row.teacherPhone
  addFormData.teacherName = row.teacherName
  addDialogVisible.value = true
}
//#endregion

//#region 删
const handleDelete = (row: IAddGradeResponseData) => {
  ElMessageBox.confirm(`正在删除班级：${row.name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    DeleteGradeApi(row.id).then(() => {
      ElMessage.success("删除成功")
      getGradeDataList()
    })
  })
}

const handleRefresh = () => {
  getGradeDataList()
}

const resetForm = () => {
  currentUpdateId.value = undefined
  addFormData.year = ""
  addFormData.note = ""
  addFormData.projectId = undefined
  addFormData.seq = undefined
  addFormData.teacherName = ""
  addFormData.teacherPhone = ""
}

/** 监听分页参数的变化 */
watch(
  [
    () => paginationData.currentPage,
    () => paginationData.pageSize,
    () => searchData.projectId,
    () => searchData.departmentId
  ],
  (newV) => {
    getGradeDataList()
    getProjectData.value.departmentId = newV[3]
  }
)
</script>

<template>
  <div class="app-container" v-loading="loading" element-loading-text="加载中">
    <el-card shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="班级名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="year" label="年级">
          <el-date-picker v-model="searchData.year" type="year" value-format="YYYY" placeholder="选择年级" />
        </el-form-item>
        <el-form-item prop="name" label="班级">
          <el-input v-model="searchData.seq" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="my-5">
      <el-form inline ref="inlineFormRef" :model="searchData">
        <el-form-item v-if="userStore.auth === '2'" prop="departmentId" label="办学单位">
          <el-select filterable v-model="searchData.departmentId" placeholder="选择办学单位">
            <el-option v-for="item in DepartmentData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="projectId" label="培训项目">
          <el-select filterable v-model="searchData.projectId" placeholder="选择项目">
            <el-option v-for="item in ProjectData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <div class="flex justify-between">
        <div v-if="hasAnthority('class.add')">
          <el-button type="primary" :icon="CirclePlus" @click="addDialogVisible = true">新增班级</el-button>
        </div>
        <div>
          <el-tooltip content="刷新表格">
            <el-button type="primary" :icon="RefreshRight" circle @click="handleRefresh" />
          </el-tooltip>
        </div>
      </div>
      <div class="mt-5">
        <el-table :data="GradeData">
          <el-table-column show-overflow-tooltip min-width="140" prop="name" label="班级名称" align="center" />
          <el-table-column min-width="140" prop="studentNum" label="班级人数" align="center" />
          <el-table-column min-width="140" prop="year" label="年级" align="center" />
          <el-table-column min-width="140" prop="seq" label="班级" align="center" />
          <el-table-column min-width="140" prop="teacherName" label="班主任姓名" align="center" />
          <el-table-column min-width="140" prop="teacherPhone" label="班主任联系电话" align="center" />
          <el-table-column show-overflow-tooltip min-width="140" prop="projectName" label="项目" align="center" />
          <el-table-column show-overflow-tooltip min-width="140" prop="trainingInfo" label="结业信息" align="center" />
          <el-table-column show-overflow-tooltip min-width="140" prop="note" label="备注" align="center" />
          <el-table-column fixed="right" label="操作" min-width="260" align="center">
            <template #default="scope">
              <el-button
                type="success"
                v-if="userInfo.authority === '2' && hasAnthority('class.graduate')"
                text
                bg
                size="small"
                @click="handleAdd(scope.row)"
                >{{ scope.row.trainingInfo ? "修改" : "添加" }}结业信息</el-button
              >
              <el-button
                v-if="hasAnthority('class.update')"
                type="primary"
                text
                bg
                size="small"
                @click="handleUpdate(scope.row)"
                >修改班级</el-button
              >
              <el-button
                v-if="hasAnthority('class.delete')"
                type="danger"
                text
                bg
                size="small"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt-5">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/修改 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="currentUpdateId === undefined ? '新增班级' : '修改班级'"
      @closed="resetForm"
      width="50%"
    >
      <el-form ref="addFormRef" :model="addFormData" :rules="addFormRules" label-width="120px" label-position="left">
        <el-form-item prop="name" label="班级名称" v-if="currentUpdateId">
          <el-input v-model="addFormData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="projectId" label="项目">
          <el-select filterable v-model="addFormData.projectId" placeholder="选择项目">
            <el-option v-for="item in ProjectData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="year" label="年级">
          <el-date-picker v-model="addFormData.year" type="year" value-format="YYYY" placeholder="选择年级" />
        </el-form-item>
        <el-form-item prop="seq" label="班级">
          <el-input v-model="addFormData.seq" placeholder="请输入" type="number" />
        </el-form-item>
        <el-form-item prop="teacherName" label="班主任姓名">
          <el-input v-model="addFormData.teacherName" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="teacherPhone" label="班主任联系电话">
          <el-input v-model="addFormData.teacherPhone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="note" label="备注">
          <el-input v-model="addFormData.note" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>

    <!--    添加结业信息-->
    <el-dialog
      v-model="addInfoDialogVisible"
      :title="currentUpdateInfoId === undefined ? '添加结业信息' : '修改结业信息'"
      @close="addInfoFormRef?.resetFields()"
      width="50%"
    >
      <el-form
        ref="addInfoFormRef"
        :model="addInfoFormData"
        :rules="addInfoFormRules"
        label-width="110px"
        label-position="left"
      >
        <el-form-item prop="year" label="结业年份">
          <el-date-picker v-model="addInfoFormData.year" type="year" value-format="YYYY" placeholder="选择结业年份" />
        </el-form-item>
        <el-form-item prop="creationTime" label="证书生成时间">
          <el-date-picker
            value-format="YYYY-MM-DD"
            v-model="addInfoFormData.creationTime"
            type="date"
            placeholder="选择证书生成时间"
          />
        </el-form-item>
        <el-form-item prop="trainingInfo" label="培训信息">
          <el-input v-model="addInfoFormData.trainingInfo" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirmAdd">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
